﻿using System.Net;
using ZenSystemService.Api.DTOs;

namespace ZenSystemService.Api.Exceptions
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch(Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exception is ConflictException)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Conflict;
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 
            }
            //context.Response.Clear();

            context.Response.WriteAsJsonAsync( new ReturnObject
            {
                Code = 0,
                ErrorMsg = exception.Message,
            });

            return Task.CompletedTask;
        }
    }
}
